//
//  MoyaCacheRequestDetail.swift
//  Common
//
//  Created by 我骑着蜗牛走天下 on 2025/11/14.
//

import UIKit

class MoyaCacheRequestDetail: ViewController<MoyaCacheRequestDetailView> {
    
    @preconcurrency @MainActor
    var item: NetworkCacheItem?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        title = "详情"
        
        // 先捕获 item 的值（只读），避免跨线程访问 Main Actor 属性
        let currentItem = self.item
        
        DispatchQueue.global(qos: .userInitiated).async {
            let formattedText = currentItem?.toFormattedString() ?? "数据为空"
            
            DispatchQueue.main.async { [weak self] in
                guard let self = self else { return }
                contatiner.textView.text = formattedText
            }
        }
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: contatiner.shareBtn)
        contatiner.shareBtn.addTarget(self, action: #selector(shareBtnCLick), for: .touchUpInside)
        
    }
    
    @objc func shareBtnCLick(){
        
        let activityVC = UIActivityViewController(activityItems: [contatiner.textView.text], applicationActivities: nil)
        present(activityVC, animated: true)
        
    }
    
}



class MoyaCacheRequestDetailView: UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        backgroundColor = .white
        
        addSubview(textView)
        
        // 关闭自动生成的AutoresizingMask约束
        textView.translatesAutoresizingMaskIntoConstraints = false

        // 添加scrollView填满父视图
        NSLayoutConstraint.activate([
            textView.topAnchor.constraint(equalTo: self.topAnchor),
            textView.leadingAnchor.constraint(equalTo: self.leadingAnchor),
            textView.trailingAnchor.constraint(equalTo: self.trailingAnchor),
            textView.bottomAnchor.constraint(equalTo: self.bottomAnchor)
        ])

        
    }
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var textView: UITextView = {
        let text = UITextView()
        text.font = UIFont.systemFont(ofSize: 15)
        text.isEditable = false
        return text
    }()
    
    lazy var shareBtn: UIButton = {
        let btn = UIButton()
        btn.setTitleColor(.blue, for: .normal)
        btn.setTitle("分享", for: .normal)
        return btn
    }()
    
}
